import socket
import os
import json
import datetime
from loguru import logger
import zipfile

def socket_service():
    while True:
        try:
            server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            server.bind(('0.0.0.0',1222))
            server.listen(3)
            break
        except Exception as e:
            logger.debug('bind wrong' + str(e))
            continue
    logger.info('Waiting connection...')
    while True:
        conn, addr = server.accept()
        logger.info('Accept new connection from {0}'.format(addr))
        try:
            receive_data(conn, addr)
        except Exception as e:
            logger.info('Handle wrong from {0},reason is {1}'.format(addr,str(e)))
            continue

def receive_data(conn, addr):
    father_path = 'E:\\project\\DataBaseData'
    logger.info('Start handle from {0}'.format(addr))
    conn.send('Hi, Welcome to the server!'.encode())
    FileDict = conn.recv(1024)
    if FileDict:
        try:
            FileDict = json.loads(FileDict.decode())
            FileName = FileDict['FileName']
            FileSize = FileDict['FileSize']
            logger.info('start recieve')
            with open(os.path.join(father_path,'NoAnalyze', FileName), 'wb') as f:
                while FileSize:
                    data = conn.recv(1024)
                    f.write(data)
                    FileSize -= len(data)
            conn.send('get it'.encode())
            logger.info('end recieve ' + FileName + ' ' + str(datetime.datetime.now()))
        except Exception as e:
            logger.debug('receive wrong' + ' ' + str(e))
            if os.path.exists(os.path.join(father_path,'NoAnalyze', FileName)):
                try:
                    z = zipfile.ZipFile(os.path.join(father_path,'NoAnalyze', FileName))
                    z.close()
                except:
                    os.remove(os.path.join(father_path,'NoAnalyze',FileName))
            conn.send('get it wrong'.encode())

if __name__ == '__main__':
    socket_service()
